package com.shilei.spring.util;

import com.shilei.spring.callback.i.Callable;
import com.shilei.spring.collection.ExpireHashSet;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.util.List;
import java.util.Properties;

/**
 * @author 石雷
 * shilei1@jiayuan.com
 * 2021/8/25/025 18:30
 */
public class PropertiesUtil {
    public static String getValue(String key){
        String property=null;

        try {
            Properties properties = new Properties();
            // 使用ClassLoader加载properties配置文件生成对应的输入流
            InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("test.properties");
            // 使用properties对象加载输入流
            properties.load(in);
            //获取key对应的value值
            property = properties.getProperty(key);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return property;
    }

    public static void callBack(Callable callable) throws IOException, InterruptedException {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        String pathStr = Thread.currentThread().getContextClassLoader().getResource(".").getPath();
        pathStr=pathStr.replace("/C:","C:");
        pathStr=pathStr.replace("/D:","D:");
        pathStr=pathStr.replace("/E:","E:");
        pathStr=pathStr.replace("/F:","F:");
        Path path = Paths.get(pathStr);
        path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY
//                ,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_CREATE
        );
        ExpireHashSet<String> names = new ExpireHashSet<>();
        while (true){
            WatchKey take = watchService.take();
            List<WatchEvent<?>> watchEvents = take.pollEvents();

            for (WatchEvent<?> pollEvent : watchEvents) {
                String context = pollEvent.context().toString();

                System.out.println(context+"|"+pollEvent.count());
                if(names.add(context,500L)){
                    if(pollEvent.count()<=1){
                        callable.call();
                    }
                }
            }
            take.reset();
        }
    }


    public static void main(String[] args) {
        System.out.println(getValue("test"));
    }
}
